package com.cdp.web.controller.system.report;

import com.cdp.common.core.domain.AjaxResult;
import com.cdp.system.dto.MakeReportDTO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

@RestController
@RequestMapping
public class DocxReport {



    @Value("${filePython.upload-pkl-excel}")
    private String uploadPklExcelPath;


    @Value("${file.upload-dir}")
    private String fileUploadDir;


    /**
     * 配比设计报告
     * @param makeReportDTO
     * @return
     */
/*
    @PostMapping("make/report/match/design")
    public AjaxResult makeReport( @RequestBody MakeReportDTO makeReportDTO) {
        // 文本占位符
        Map<String, String> textReplaceMap = new HashMap<>();
        textReplaceMap.put("${target}", makeReportDTO.getTarget());
        textReplaceMap.put("${name}", makeReportDTO.getName());
        textReplaceMap.put("${max}", makeReportDTO.getMaxAppraise());
        textReplaceMap.put("${min}", makeReportDTO.getPopulationNumber());


        textReplaceMap.put("${3dfloor}", makeReportDTO.getTargetDecisionfloor3d());
        textReplaceMap.put("${3dupper}", makeReportDTO.getTargetDecisionupper3d());



        textReplaceMap.put("${7dfloor}", makeReportDTO.getTargetDecisionfloor7d());
        textReplaceMap.put("${7dupper}", makeReportDTO.getTargetDecisionupper7d());


        textReplaceMap.put("${28dfloor}", makeReportDTO.getTargetDecisionfloor28d());
        textReplaceMap.put("${28dupper}", makeReportDTO.getTargetDecisionupper28d());




        textReplaceMap.put("${slumpFloor}", makeReportDTO.getTargetDecisionfloorSlumps());
        textReplaceMap.put("${slumPupper}", makeReportDTO.getTargetDecisionupperSlumps());


        textReplaceMap.put("${costFloor}", makeReportDTO.getTargetDecisionfloorCost());
        textReplaceMap.put("${costPupper}", makeReportDTO.getTargetDecisionupperCost());



        // 新的特征数值决策
        textReplaceMap.put("${waterFloor}", makeReportDTO.getWaterFloor());
        textReplaceMap.put("${waterUpper}", makeReportDTO.getWaterUpper());
        textReplaceMap.put("${cementFloor}", makeReportDTO.getCementFloor());
        textReplaceMap.put("${cementUpper}", makeReportDTO.getCementUpper());
        textReplaceMap.put("${machineSandFloor}", makeReportDTO.getMachineSandFloor());
        textReplaceMap.put("${machineSandUpper}", makeReportDTO.getMachineSandUpper());
        textReplaceMap.put("${gravelFloor}", makeReportDTO.getGravelFloor());
        textReplaceMap.put("${gravelUpper}", makeReportDTO.getGravelUpper());
        textReplaceMap.put("${slagFloor}", makeReportDTO.getSlagFloor());
        textReplaceMap.put("${slagUpper}", makeReportDTO.getSlagUpper());
        textReplaceMap.put("${flyAshFloor}", makeReportDTO.getFlyAshFloor());
        textReplaceMap.put("${flyAshUpper}", makeReportDTO.getFlyAshUpper());
        textReplaceMap.put("${waterReducerFloor}", makeReportDTO.getWaterReducerFloor());
        textReplaceMap.put("${waterReducerUpper}", makeReportDTO.getWaterReducerUpper());
        textReplaceMap.put("${synergistFloor}", makeReportDTO.getSynergistFloor());
        textReplaceMap.put("${synergistUpper}", makeReportDTO.getSynergistUpper());


        // 新的特征比例决策
        textReplaceMap.put("${cementitiousMaterialFloor}", makeReportDTO.getCementitiousMaterialFloor());
        textReplaceMap.put("${cementitiousMaterialUpper}", makeReportDTO.getCementitiousMaterialUpper());
        textReplaceMap.put("${waterCementRatioFloor}", makeReportDTO.getWaterCementRatioFloor());
        textReplaceMap.put("${waterCementRatioUpper}", makeReportDTO.getWaterCementRatioUpper());
        textReplaceMap.put("${waterLimeRatioFloor}", makeReportDTO.getWaterLimeRatioFloor());
        textReplaceMap.put("${waterLimeRatioUpper}", makeReportDTO.getWaterLimeRatioUpper());
        textReplaceMap.put("${sandCementRatioFloor}", makeReportDTO.getSandCementRatioFloor());
        textReplaceMap.put("${sandCementRatioUpper}", makeReportDTO.getSandCementRatioUpper());
        textReplaceMap.put("${sandRatioFloor}", makeReportDTO.getSandRatioFloor());
        textReplaceMap.put("${sandRatioUpper}", makeReportDTO.getSandRatioUpper());

        // 新的总量决策
        textReplaceMap.put("${totalMaterialMassFloor}", makeReportDTO.getTotalMaterialMassFloor());
        textReplaceMap.put("${totalMaterialMassUpper}", makeReportDTO.getTotalMaterialMassUpper());

        // 图片占位符
        Map<String, String> imageReplaceMap = new HashMap<>();
        imageReplaceMap.put("${picture1}", makeReportDTO.getPicture1());
        imageReplaceMap.put("${picture2}", makeReportDTO.getPicture2());


        // 当前日期
        LocalDateTime nowData = LocalDateTime.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String dateStr = nowData.format(dateFormatter);
        textReplaceMap.put("${nowDate}", dateStr);

        String excelPath = makeReportDTO.getExcelPath();
        // Excel 文件路径和模板路径
        // String excelPath = "C:\\Users\\Administrator\\Desktop\\算法测试用\\算法照片\\配比设计\\17459089673827678.xlsx";

        //  String templatePath = "C:\\Users\\Administrator\\Desktop\\文档\\machDesignTemplate.docx";
        String templatePath = uploadPklExcelPath + "machDesignTemplate.docx";

        String directoryPath =    fileUploadDir;
        //String directoryPath = "C:\\Users\\Administrator\\Desktop\\文档\\报告\\";

        try {
            // 读取 Excel 数据
            List<List<String>> excelData = extractExcelDataV2(excelPath);

            // 创建 Excel 数据图片
            BufferedImage image = createImageFromExcel(excelData);

            // 保存图片并获取图片路径
            String imagePath = saveImage(image, directoryPath);

            // 将图片路径插入到占位符映射
            imageReplaceMap.put("${picture3}", imagePath);


            List<List<String>> excelData5 = extractExcelData5(excelPath);
            // 创建 Excel 数据图片
            BufferedImage image5 = createImageFromExcel(excelData5);
            // 保存图片并获取图片路径
            String imagePath5 = saveImage5(image5, directoryPath);


            // 将图片路径插入到占位符映射
            imageReplaceMap.put("${picture4}", imagePath5);


            // 生成报告（使用之前的代码）
            if (!Files.exists(Paths.get(directoryPath))) {
                Files.createDirectories(Paths.get(directoryPath));
            }

            try (InputStream is = new FileInputStream(templatePath);
                 XWPFDocument doc = new XWPFDocument(is)) {

                // 替换段落
                for (XWPFParagraph paragraph : doc.getParagraphs()) {
                    replaceInParagraph(paragraph, textReplaceMap, imageReplaceMap);
                }

                // 替换表格
                for (XWPFTable table : doc.getTables()) {
                    for (XWPFTableRow row : table.getRows()) {
                        for (XWPFTableCell cell : row.getTableCells()) {
                            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                                replaceInParagraph(paragraph, textReplaceMap, imageReplaceMap);
                            }
                        }
                    }
                }

                long timestamp = System.currentTimeMillis();
                int randomNum = new Random().nextInt(10000);
                String fileName = timestamp + "_" + randomNum + ".docx";
                String outPath = directoryPath + fileName;



                try (OutputStream os = new FileOutputStream(outPath)) {
                    doc.write(os);
                }

                return AjaxResult.success(outPath);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("报告生成失败！");
        }
    }


*/

    /**
     * 配比设计报告
     * @param makeReportDTO
     * @return
     */
    @PostMapping("make/report/match/design")
    public AjaxResult makeReport(@RequestBody MakeReportDTO makeReportDTO) {
        // 文本占位符（增加空值处理）
        Map<String, String> textReplaceMap = new HashMap<>();

        // 模型概况参数
        textReplaceMap.put("${target}", handleNull(makeReportDTO.getTarget()));
        textReplaceMap.put("${name}", handleNull(makeReportDTO.getName()));
        textReplaceMap.put("${max}", handleNull(makeReportDTO.getMaxAppraise()));
        textReplaceMap.put("${min}", handleNull(makeReportDTO.getPopulationNumber()));

        // 目标决策表格参数
        textReplaceMap.put("${3dfloor}", handleNull(makeReportDTO.getTargetDecisionfloor3d()));
        textReplaceMap.put("${3dupper}", handleNull(makeReportDTO.getTargetDecisionupper3d()));
        textReplaceMap.put("${7dfloor}", handleNull(makeReportDTO.getTargetDecisionfloor7d()));
        textReplaceMap.put("${7dupper}", handleNull(makeReportDTO.getTargetDecisionupper7d()));
        textReplaceMap.put("${28dfloor}", handleNull(makeReportDTO.getTargetDecisionfloor28d()));
        textReplaceMap.put("${28dupper}", handleNull(makeReportDTO.getTargetDecisionupper28d()));
        textReplaceMap.put("${slumpFloor}", handleNull(makeReportDTO.getTargetDecisionfloorSlumps()));
        textReplaceMap.put("${slumPupper}", handleNull(makeReportDTO.getTargetDecisionupperSlumps()));
        textReplaceMap.put("${costFloor}", handleNull(makeReportDTO.getTargetDecisionfloorCost()));
        textReplaceMap.put("${costPupper}", handleNull(makeReportDTO.getTargetDecisionupperCost()));

        // 特征数值决策表格参数
        textReplaceMap.put("${waterFloor}", handleNull(makeReportDTO.getWaterFloor()));
        textReplaceMap.put("${waterUpper}", handleNull(makeReportDTO.getWaterUpper()));
        textReplaceMap.put("${cementFloor}", handleNull(makeReportDTO.getCementFloor()));
        textReplaceMap.put("${cementUpper}", handleNull(makeReportDTO.getCementUpper()));
        textReplaceMap.put("${machineSandFloor}", handleNull(makeReportDTO.getMachineSandFloor()));
        textReplaceMap.put("${machineSandUpper}", handleNull(makeReportDTO.getMachineSandUpper()));
        textReplaceMap.put("${gravelFloor}", handleNull(makeReportDTO.getGravelFloor()));
        textReplaceMap.put("${gravelUpper}", handleNull(makeReportDTO.getGravelUpper()));
        textReplaceMap.put("${slagFloor}", handleNull(makeReportDTO.getSlagFloor()));
        textReplaceMap.put("${slagUpper}", handleNull(makeReportDTO.getSlagUpper()));
        textReplaceMap.put("${flyAshFloor}", handleNull(makeReportDTO.getFlyAshFloor()));
        textReplaceMap.put("${flyAshUpper}", handleNull(makeReportDTO.getFlyAshUpper()));
        textReplaceMap.put("${waterReducerFloor}", handleNull(makeReportDTO.getWaterReducerFloor()));
        textReplaceMap.put("${waterReducerUpper}", handleNull(makeReportDTO.getWaterReducerUpper()));
        textReplaceMap.put("${synergistFloor}", handleNull(makeReportDTO.getSynergistFloor()));
        textReplaceMap.put("${synergistUpper}", handleNull(makeReportDTO.getSynergistUpper()));

        // 特征比例决策表格参数
        textReplaceMap.put("${cementitiousMaterialFloor}", handleNull(makeReportDTO.getCementitiousMaterialFloor()));
        textReplaceMap.put("${cementitiousMaterialUpper}", handleNull(makeReportDTO.getCementitiousMaterialUpper()));
        textReplaceMap.put("${waterCementRatioFloor}", handleNull(makeReportDTO.getWaterCementRatioFloor()));
        textReplaceMap.put("${waterCementRatioUpper}", handleNull(makeReportDTO.getWaterCementRatioUpper()));
        textReplaceMap.put("${waterLimeRatioFloor}", handleNull(makeReportDTO.getWaterLimeRatioFloor()));
        textReplaceMap.put("${waterLimeRatioUpper}", handleNull(makeReportDTO.getWaterLimeRatioUpper()));
        textReplaceMap.put("${sandCementRatioFloor}", handleNull(makeReportDTO.getSandCementRatioFloor()));
        textReplaceMap.put("${sandCementRatioUpper}", handleNull(makeReportDTO.getSandCementRatioUpper()));
        textReplaceMap.put("${sandRatioFloor}", handleNull(makeReportDTO.getSandRatioFloor()));
        textReplaceMap.put("${sandRatioUpper}", handleNull(makeReportDTO.getSandRatioUpper()));

        // 总量决策表格参数
        textReplaceMap.put("${totalMaterialMassFloor}", handleNull(makeReportDTO.getTotalMaterialMassFloor()));
        textReplaceMap.put("${totalMaterialMassUpper}", handleNull(makeReportDTO.getTotalMaterialMassUpper()));

        // 图片占位符
        Map<String, String> imageReplaceMap = new HashMap<>();
        imageReplaceMap.put("${picture1}", makeReportDTO.getPicture1() != null ? makeReportDTO.getPicture1() : "");
        imageReplaceMap.put("${picture2}", makeReportDTO.getPicture2() != null ? makeReportDTO.getPicture2() : "");

        // 当前日期
        LocalDateTime nowData = LocalDateTime.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String dateStr = nowData.format(dateFormatter);
        textReplaceMap.put("${nowDate}", dateStr);

        String excelPath = makeReportDTO.getExcelPath();
        String templatePath = uploadPklExcelPath + "machDesignTemplate.docx";
        String directoryPath = fileUploadDir;

        try {
            // 读取并处理Excel数据（保持原逻辑）
            List<List<String>> excelData = extractExcelDataV2(excelPath);
            BufferedImage image = createImageFromExcel(excelData);
            String imagePath = saveImage(image, directoryPath);
            imageReplaceMap.put("${picture3}", imagePath);

            List<List<String>> excelData5 = extractExcelData5(excelPath);
            BufferedImage image5 = createImageFromExcel(excelData5);
            String imagePath5 = saveImage5(image5, directoryPath);
            imageReplaceMap.put("${picture4}", imagePath5);

            // 生成文档（保持原逻辑）
            if (!Files.exists(Paths.get(directoryPath))) {
                Files.createDirectories(Paths.get(directoryPath));
            }

            try (InputStream is = new FileInputStream(templatePath);
                 XWPFDocument doc = new XWPFDocument(is)) {

                // 替换段落和表格中的占位符
                for (XWPFParagraph paragraph : doc.getParagraphs()) {
                    replaceInParagraph(paragraph, textReplaceMap, imageReplaceMap);
                }
                for (XWPFTable table : doc.getTables()) {
                    for (XWPFTableRow row : table.getRows()) {
                        for (XWPFTableCell cell : row.getTableCells()) {
                            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                                replaceInParagraph(paragraph, textReplaceMap, imageReplaceMap);
                            }
                        }
                    }
                }

                // 生成文件名
                long timestamp = System.currentTimeMillis();
                int randomNum = new Random().nextInt(10000);
                String fileName = timestamp + "_" + randomNum + ".docx";
                String outPath = directoryPath + fileName;

                try (OutputStream os = new FileOutputStream(outPath)) {
                    doc.write(os);
                }
                return AjaxResult.success(outPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("报告生成失败！");
        }
    }
    // 空值处理工具方法
    private String handleNull(String value) {
        return value == null || value.trim().isEmpty() ? "/" : value;
    }

    private List<List<String>> extractExcelDataV2(String excelPath) {
        List<List<String>> excelData = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(excelPath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(1); // 获取第一个工作表

            for (int i = 0; i < 11; i++) { // 处理前 10 行
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    if (cell.getCellType() == CellType.NUMERIC) {
                        // 数字格式化为保留两位小数
                        double value = cell.getNumericCellValue();
                        rowData.add(String.format("%.2f", value));
                    } else if (cell.getCellType() == CellType.STRING) {
                        rowData.add(cell.getStringCellValue());
                    }
                }
                excelData.add(rowData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return excelData;
    }


    /**
     * 读取 Excel 数据并提取前 5 行，数字格式化为两位小数
     */
    private List<List<String>> extractExcelData5(String excelPath) {
        List<List<String>> excelData = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(excelPath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(1); // 获取第一个工作表

            for (int i = 0; i < 6; i++) { // 处理前 10 行
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    if (cell.getCellType() == CellType.NUMERIC) {
                        // 数字格式化为保留两位小数
                        double value = cell.getNumericCellValue();
                        rowData.add(String.format("%.2f", value));
                    } else if (cell.getCellType() == CellType.STRING) {
                        rowData.add(cell.getStringCellValue());
                    }
                }
                excelData.add(rowData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return excelData;
    }



    /**
     * 将 Excel 数据渲染为图片
     */
    private BufferedImage createImageFromExcel(List<List<String>> excelData) {
        int cellWidth = 100; // 每个单元格的宽度
        int cellHeight = 30; // 每个单元格的高度
       // int width = cellWidth * 10; // 假设最多 10 列

        int columnCount = excelData.get(0).size(); // 获取列数
        int width = cellWidth * columnCount;


        int height = cellHeight * (excelData.size() + 1); // 行数 + 1 是为了绘制表头

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        g2d.setColor(Color.WHITE); // 背景颜色
        g2d.fillRect(0, 0, width, height);

        // 使用支持中文的字体（如“黑体”）来避免中文乱码问题
       // Font font = new Font("SimHei", Font.PLAIN, 12); // 设置字体为黑体
        Font font = new Font("SimSun", Font.PLAIN, 14); // 设置为宋体，字号为四号（14磅）

        g2d.setFont(font);
        g2d.setColor(Color.BLACK); // 文字颜色

        // 绘制表头
        int y = 0;
        List<String> headers = excelData.get(0); // 获取表头数据
        int x = 0;
        for (String header : headers) {
            g2d.drawRect(x, y, cellWidth, cellHeight); // 绘制单元格
            FontMetrics fontMetrics = g2d.getFontMetrics();
            int stringWidth = fontMetrics.stringWidth(header);
            int xPos = x + (cellWidth - stringWidth) / 2; // 确保文本水平居中
            int yPos = y + (cellHeight + fontMetrics.getAscent()) / 2 - fontMetrics.getDescent(); // 确保文本垂直居中
            g2d.drawString(header, xPos, yPos); // 绘制居中的文字
            x += cellWidth;
        }
        y += cellHeight;

        // 绘制数据行
        for (int i = 1; i < excelData.size(); i++) {
            x = 0;
            for (String cell : excelData.get(i)) {
                g2d.drawRect(x, y, cellWidth, cellHeight);
                FontMetrics fontMetrics = g2d.getFontMetrics();
                int stringWidth = fontMetrics.stringWidth(cell);
                int xPos = x + (cellWidth - stringWidth) / 2; // 确保文本水平居中
                int yPos = y + (cellHeight + fontMetrics.getAscent()) / 2 - fontMetrics.getDescent(); // 确保文本垂直居中
                g2d.drawString(cell, xPos, yPos);
                x += cellWidth;
            }
            y += cellHeight;
        }

        g2d.dispose();
        return bufferedImage;
    }

    /**
     * 保存图片并返回图片路径
     */
    private String saveImage(BufferedImage image, String directoryPath) throws IOException {
        // 创建目录（如果不存在）
        File dir = new File(directoryPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long timestamp = System.currentTimeMillis();
        int randomNum = new Random().nextInt(10000);
        String url = timestamp + String.valueOf(randomNum);


        // 保存为 PNG 格式的图片
        File imageFile = new File(directoryPath +url+ "excel_image.png");
        ImageIO.write(image, "png", imageFile);
        return imageFile.getAbsolutePath();
    }
    private String saveImage5(BufferedImage image, String directoryPath) throws IOException {
        // 创建目录（如果不存在）
        File dir = new File(directoryPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long timestamp = System.currentTimeMillis();
        int randomNum = new Random().nextInt(10000);
        String url = timestamp + String.valueOf(randomNum);


        // 保存为 PNG 格式的图片
        File imageFile = new File(directoryPath +url+ "excel_image5.png");
        ImageIO.write(image, "png", imageFile);
        return imageFile.getAbsolutePath();
    }
    /**
     * 替换段落中的占位符，文字和图片
     */
    private void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> textReplaceMap, Map<String, String> imageReplaceMap) {
        StringBuilder fullText = new StringBuilder();
        List<XWPFRun> runs = paragraph.getRuns();

        // 拼接完整文本
        for (XWPFRun run : runs) {
            if (run.getText(0) != null) {
                fullText.append(run.getText(0));
            }
        }

        String replacedText = fullText.toString();

        // 替换文字
        for (Map.Entry<String, String> entry : textReplaceMap.entrySet()) {
            replacedText = replacedText.replace(entry.getKey(), entry.getValue());
        }

        // 替换图片（如果包含图片占位符，则清空占位符，准备后面插图）
        Map<String, String> imagesToInsert = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : imageReplaceMap.entrySet()) {
            if (replacedText.contains(entry.getKey())) {
                replacedText = replacedText.replace(entry.getKey(), ""); // 占位符替换为空
                imagesToInsert.put(entry.getKey(), entry.getValue());    // 记录后面插图
            }
        }

        // 清空原 runs
        for (int i = runs.size() - 1; i >= 0; i--) {
            paragraph.removeRun(i);
        }

        // 写入新的文本 run
        if (!replacedText.isEmpty()) {
            XWPFRun newRun = paragraph.createRun();
            newRun.setText(replacedText);
        }


        Map<String, int[]> imageSizeMap = new HashMap<>();
        imageSizeMap.put("${picture1}", new int[]{200, 200});
        imageSizeMap.put("${picture2}", new int[]{200, 200});
        imageSizeMap.put("${picture3}", new int[]{400, 200});
        imageSizeMap.put("${picture4}", new int[]{400, 100});

        for (Map.Entry<String, String> entry : imagesToInsert.entrySet()) {
            String imgPath = entry.getValue();
            try (InputStream imgInputStream = new FileInputStream(imgPath)) {
                XWPFRun imgRun = paragraph.createRun();

                int width = 300;
                int height = 200;
                if (imageSizeMap.containsKey(entry.getKey())) {
                    width = imageSizeMap.get(entry.getKey())[0];
                    height = imageSizeMap.get(entry.getKey())[1];
                }

                imgRun.addPicture(imgInputStream, getPictureType(imgPath), imgPath, Units.toEMU(width), Units.toEMU(height));
                imgRun.addBreak(); // 添加换行符，实现图片上下对齐效果
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 判断图片类型
     */
    private int getPictureType(String imgFileName) {
        String lowerCase = imgFileName.toLowerCase();
        if (lowerCase.endsWith(".emf")) {
            return Document.PICTURE_TYPE_EMF;
        } else if (lowerCase.endsWith(".wmf")) {
            return Document.PICTURE_TYPE_WMF;
        } else if (lowerCase.endsWith(".pict")) {
            return Document.PICTURE_TYPE_PICT;
        } else if (lowerCase.endsWith(".jpeg") || lowerCase.endsWith(".jpg")) {
            return Document.PICTURE_TYPE_JPEG;
        } else if (lowerCase.endsWith(".png")) {
            return Document.PICTURE_TYPE_PNG;
        } else if (lowerCase.endsWith(".dib")) {
            return Document.PICTURE_TYPE_DIB;
        } else if (lowerCase.endsWith(".gif")) {
            return Document.PICTURE_TYPE_GIF;
        } else if (lowerCase.endsWith(".tiff")) {
            return Document.PICTURE_TYPE_TIFF;
        } else if (lowerCase.endsWith(".eps")) {
            return Document.PICTURE_TYPE_EPS;
        } else if (lowerCase.endsWith(".bmp")) {
            return Document.PICTURE_TYPE_BMP;
        } else if (lowerCase.endsWith(".wpg")) {
            return Document.PICTURE_TYPE_WPG;
        } else {
            return Document.PICTURE_TYPE_PNG;
        }
    }
















}
